<template>
  <div>
    <el-card>
      <div class="form">
        <el-form :inline="true">
          <el-form-item label="实验室名称">
            <el-input v-model="formModel.labName" placeholder="请输入实验室名称"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formModel.labStatus" placeholder="请选择">
              <el-option label="区域一" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button>重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div slot="header">
        <el-button type="primary" size="small" @click="add">新建</el-button>
        <el-button type="danger" size="small">删除</el-button>
      </div>
      <!-- 提示部分 -->
      <div class="point">
        <div class="point-text">
          <span>
            已经选择了2项 可容纳人数：58
            <el-button type="text">清空</el-button>
          </span>
        </div>
      </div>
      <!-- 主体部分的表格 -->
      <el-table stripe :data="tableData.row" style="width: 100%" :current-row-key="tableData.row.id">
        <el-table-column
          type="selection"
          width="55"
        >
        </el-table-column>
        <el-table-column
          type="index"
          label="编号"
          width="50"
        >
        </el-table-column>
        <el-table-column label="名称">
          <template slot-scope="slotProps">
            {{slotProps.row.name}}
          </template>
        </el-table-column>
        <el-table-column label="用途">
          <template slot-scope="slotProps">
            {{slotProps.row.purpose}}
          </template>
        </el-table-column>
        <el-table-column sortable label="可容纳人数">
          <template slot-scope="slotProps">
            {{slotProps.row.maxNumber}}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="slotProps">
            {{slotProps.row.isOpen?"开放":"暂未开放"}}
          </template>
        </el-table-column>
        <!-- <el-table-column label="关联实验室类型">
          <template slot-scope="slotProps">
            <el-button type="text">5</el-button>
          </template>
        </el-table-column> -->
        <el-table-column label="更新时间">
          <template slot-scope="slotProps">
            <!-- {{slotProps.row.isOpen?"开放":"暂未开放"}} -->
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="slotProps">
            <el-button type="text" @click="edit(slotProps.$index)">编辑</el-button>
            <el-button type="text" @click="del(slotProps.$index)">删除</el-button>
            <el-button type="text" @click="relate(slotProps.$index)">关联实验类型</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!-- 底部的翻页器 -->
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :pager-count="5"
          :total="page.total"
          :page-size="page.pageSize"
          :current-page="page.currentPage"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 点击删除按钮出现的弹框 -->
    <el-dialog
      :title="delDialog.title"
      :visible.sync="delDialog.show"
      width="30%"
      center
    >
      <span>{{delDialog.content}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delDialog.show = false">取 消</el-button>
        <el-button type="primary" @click="delSure">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击添加、编辑出现的弹框，弹框主体是表单 -->
    <el-dialog
      fullscreen
      :title="adedDialog.title"
      :visible.sync="adedDialog.show"
      @close="handleDialogClose(`formData`)"
      width="800px"
      center
    >
      <el-form ref="formData" :model="formData" :rules="ruleForm" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item v-if="!adedDialog.showButton" label="可容纳人数" prop="maxNumber">
          <el-radio-group v-model="radioNumber">
            <el-radio :label="1">固定值</el-radio>
            <el-radio :label="2">按选择设备数量</el-radio>
          </el-radio-group>
          <div v-if="radioNumber === 1">
            <el-input-number v-model="formData.maxNumber" controls-position="right" :min="1"></el-input-number>
          </div>
          <div v-else>
            <el-popover
              placement="right"
              width="400"
              trigger="click"
            >
            <div>
              <el-form :inline="true" :model="dialogTable" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="dialogTable.deviceName" placeholder="请输入设备名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchDevice">搜 索</el-button>
                </el-form-item>
              </el-form>
              <el-table
                :data="dialogTable.deviceData"
                style="width: 100%"
                border
                highlight-current-row
                @current-change="handleTableCurrentChange"
                :current-row-key="dialogTable.deviceData.id"
                max-height="350"
              >
                <el-table-column
                  type="index"
                  label="编号"
                  width="50"
                >
                </el-table-column>
                <el-table-column label="设备名称">
                  <template slot-scope="slotProps">
                    {{slotProps.row.name}}
                  </template>
                </el-table-column>
                <el-table-column label="设备型号">
                  <template slot-scope="slotProps">
                    {{slotProps.row.model}}
                  </template>
                </el-table-column>
                <el-table-column label="数量">
                  <template slot-scope="slotProps">
                    {{slotProps.row.count}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-button slot="reference">选择设备</el-button>
            </el-popover>
            <br>
            <div v-if="dialogTable.formTableData.length">
              <el-table :data="dialogTable.formTableData" :current-row-key="dialogTable.formTableData.id" style="width: 100%">
                <el-table-column label="设备名称">
                  <template slot-scope="slotProps">
                    {{slotProps.row.name}}
                  </template>
                </el-table-column>
                <el-table-column label="设备型号">
                  <template slot-scope="slotProps">
                    {{slotProps.row.model}}
                  </template>
                </el-table-column>
                <el-table-column label="数量">
                  <template slot-scope="slotProps">
                    {{slotProps.row.count}}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="用途" prop="purpose">
          <el-input v-model="formData.purpose"></el-input>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="描述">
          <wangeditor :editorHtml="formData.description" @getEditorCon="getEditor"></wangeditor>
        </el-form-item>
        <el-form-item label="是否开放" prop="isOpen">
          <el-select v-model="formData.isOpen" placeholder="请选择--">
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="restForm(`formData`)">重 置</el-button>
        <el-button type="primary" v-show="adedDialog.showButton" @click="editSure(`formData`)">编 辑</el-button>
        <el-button type="primary" v-show="!adedDialog.showButton" @click="addSure(`formData`)">立即添加</el-button>
        <el-button @click="adedDialog.show = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 点击关联实验的时候，弹出的弹框 ，弹框主体内容为实验树 -->
    <el-dialog
      :title="relDialog.title"
      :visible.sync="relDialog.show"
      width="500px"
      center
    >
      <!-- 实验树 -->
      <el-tree :data="experimentTreeData" :props="defaultProps" show-checkbox ref="tree" node-key="id"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="relDialog.show = false">取 消</el-button>
        <el-button type="primary" @click="relSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import request from '@/utils/request'
import wangeditor from '@/components/wangEditor/index.vue'
import { isvalidInt } from '@/utils/validate'
export default {
  components: {
    wangeditor
  },
  created() {
    this.getList()
    this.getExperimentList()
    this.getDeviceList()
  },
  data() {
    const validInt = (rule, value, callback) => { // 整数验证
      if (!value && this.radioNumber === 1) {
        callback(new Error('不能为空'))
      } else if (!isvalidInt(value) && this.radioNumber === 1) {
        callback(new Error('请输入整数'))
      } else {
        callback()
      }
    }
    return {
      formModel: {
        labName: '',
        labStatus: ''
      },
      page: { // 页面相关数据
        total: 10, // 数据总数
        pageSize: 10, // 一页中最多的数据数
        currentPage: 1, // 当前页面
        experimentTotal: 10, // 特殊需求下的数据
        PageExperimentSize: 1000,
        currentExperimentPage: 1
      },
      tableData: {
        row: []
      },
      inputSearch: '',
      delDialog: {
        show: false,
        content: '',
        title: '删除',
        id: ''
      },
      adedDialog: {
        show: false,
        content: '',
        title: '',
        showButton: ''
      },
      relDialog: {
        title: '选择关联的实验类型',
        show: false
      },
      formData: {},
      currentIndex: {
        editIndex: '',
        delIndex: ''
      }, // 当前所操作的数据的下标
      currentLabId: '',
      experimentTreeData: [], // 实验树的值
      defaultProps: {
        label: 'name',
        id: 'id',
        children: 'children'
      },
      editorData: '',
      editorAll: {},
      options: [{
        value: 0,
        label: '暂未开放'
      }, {
        value: 1,
        label: '开放预约'
      }],
      ruleForm: { // 表单验证
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        maxNumber: [
          { required: true, validator: validInt, trigger: 'blur' }
        ],
        purpose: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        isOpen: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      radioNumber: 1, // 使用单选框来控制获取实验室可容纳人数的方式
      dialogTable: {
        deviceData: [], // 设备表格中的数据
        currentRow: '',
        formTableData: [],
        deviceName: ''
      }
    }
  },
  methods: {
    // 获取富文本编辑器中的内容
    getEditor(data) {
      this.editorAll = data
      this.editorData = data.txt.html()
    },
    // 根据id查询实验室详细信息
    getListOfId(id) {
      request.get(`/items/lab/${id}`).then(res => {
        this.formData = res.content
        if (this.editorAll.txt !== undefined) { // 第一次点击editorAll是个空对象，判断一下  第一次不用赋值
          this.editorAll.txt.html(this.formData.description)
        }
      })
    },
    // 查询实验室分页信息，获取实验室列表
    getList() {
      return request.get('/items/lab', { params: {
        size: this.page.pageSize,
        current: this.page.currentPage
      }}).then(res => {
        this.tableData.row = res.content.records
        this.page.total = res.content.total
      })
    },
    // 获取所有的实验列表
    getExperimentList() {
      request.get('/labs/experitype/page', { params: {
        size: this.page.PageExperimentSize,
        current: this.page.currentExperimentPage
      }}).then(res => {
        this.experimentTreeData = res.content.records
        this.page.experimentTotal = res.content.total
      })
    },
    // 获取某实验室下的实验列表的id
    getLabAndExperimentIds() {
      request.get('/labs/experitype/page').then(res => {
        this.hasExperimentIds = []
        for (let i = 0; i < res.content.records.length; i++) {
          this.hasExperimentIds[i] = res.content.records[i].experimentId
        }
      }).then(() => {
        this.$refs.tree.setCheckedKeys(this.hasExperimentIds)
      })
    },
    // 获取弹框中的设备的数据
    getDeviceList() {
      request.get('/items/device', { params: {
        size: 100,
        current: 1,
        name: this.dialogTable.deviceName
      }}).then(res => {
        this.dialogTable.deviceData = res.content.records
      })
    },
    // 删除操作
    del(index) {
      this.currentIndex.delIndex = index
      this.delDialog.content = '您确定删除 ' + this.tableData.row[this.currentIndex.delIndex].name + ' 吗？'
      this.delDialog.id = this.tableData.row[this.currentIndex.delIndex].id
      this.delDialog.show = true
    },
    delSure() {
      this.delDialog.show = false
      request.delete(`/items/lab/${this.delDialog.id}`).then(res => {
        if (res.code === 0) {
          this.getList() // 删除后重新加载页面
        }
      })
    },
    // 编辑操作
    edit(index) {
      this.currentIndex.editIndex = index
      var currentId = this.tableData.row[this.currentIndex.editIndex].id
      this.getListOfId(currentId)
      this.adedDialog.title = '编辑'
      this.adedDialog.show = true
      this.adedDialog.showButton = true
    },
    editSure(formName) { // 提交根据id查询得到的详细数据
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.formData.description = this.editorData
          request.put('/items/lab/update', {
            ...this.formData
          }).then(res => { // 以对象形式传参
            if (res.code === 0) {
              this.getList()
            } else {
              this.$message.warning(res.content)
            }
            this.adedDialog.show = false
          })
        }
      })
    },
    // 关联实验操作
    relate(index) {
      this.currentLabId = this.tableData.row[index].id
      this.relDialog.show = true
      this.getLabAndExperimentIds()
    },
    relSure() {
      request.post(`/items/labAndExperiment/bylab/${this.currentLabId}`,
        this.$refs.tree.getCheckedKeys()
      ).then(res => {
        this.$message.success(res.content)
        this.$refs.tree.setCheckedKeys([])
        this.relDialog.show = false
      })
    },
    // 添加操作
    add() {
      this.formData = {} // 富文本编辑器的重置有问题
      this.formData.description = ''
      if (this.editorAll.txt !== undefined) {
        this.editorAll.txt.clear()
      }
      this.adedDialog.title = '添加'
      this.adedDialog.show = true
      this.adedDialog.showButton = false
    },
    addSure(formName) { //  经过通信，formData与表单中的数据绑定
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.formData.description = this.editorData
          if (this.radioNumber === 1) { // 用户自定义可容纳数量
            request.post('/items/lab/add', {
              ...this.formData
            }).then(res => {
              if (res.code === 0) {
                this.getList()
              } else {
                console.log('失败')
                this.$message.warning(res.content)
              }
              this.adedDialog.show = false
            })
          } else if (this.radioNumber === 2) { // 用户根据关联一级设备获得相应的可容纳人数
            this.formData.count = ''
            request.post('/items/lab/add', {
              deviceId: this.dialogTable.formTableData[0].id,
              ...this.formData
            }).then(res => {
              if (res.code === 0) {
                this.getList()
              } else {
                console.log('失败')
                this.$message.warning(res.content)
              }
              this.adedDialog.show = false
            })
          }
        }
      })
    },
    // 单选表格中的数据
    handleTableCurrentChange(obj) {
      // this.dialogTable.formTableData[0] = { ...obj } // 由于js本身的限制，vue不能检测该方式变动的数组
      this.dialogTable.formTableData.splice(0, 1, { ...obj })
    },
    // 翻页时触发该函数
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    },
    // 关闭弹窗时会触发该钩子，重置表单
    handleDialogClose(formName) {
      this.adedDialog.show = false
      this.dialogTable.formTableData = []
      this.dialogTable.deviceName = ''
      this.radioNumber = 1
      this.restForm(formName)
    },
    // 重置表单函数
    restForm(formName) {
      this.$refs[formName].resetFields() // 重置
      // this.formData = {} // 将表单置空
    },
    // 搜索设备
    searchDevice() {
      this.getDeviceList()
    }
  }
}
</script>

<style scoped>
.point {
  width: 100%;
  height: 40px;
  margin-top: 8px;
  background-color: #e6f7f7;
  border: 1px solid rgba(186, 231, 255, 1);
  border-radius: 4px;
  box-shadow: none;
  font-size: 14px;
  text-align: left;
}
.point-text {
  margin-left: 14px;
  line-height: 40px;
}
.pagination {
  float: right;
  margin-bottom: 15px;
}
</style>
